package com.bonc.web.cors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 跨域过滤器
 * @Author: ChenZhiXiang
 * @CreateDate: 2018/12/19 0019 15:00
 * @Version: 1.0
 */
public class CorsFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CorsFilter.class);

    //跨域标志
    private Boolean corsFlag;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        corsFlag = Boolean.valueOf(filterConfig.getInitParameter("corsFlag"));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain chain)
            throws IOException, ServletException {
        logger.info("跨域开始----------");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String origin = req.getHeader("Origin");
        if (corsFlag) {
            resp.setHeader("Access-Control-Allow-Origin", origin);
            resp.setContentType("application/json1;charset=UTF-8");
            resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            resp.setHeader("Access-Control-Max-Age", "3600");
            //表明服务器支持的所有头信息字段
            resp.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
            //如果要把Cookie发到服务器，需要指定Access-Control-Allow-Credentials字段为true;
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setHeader("XDomainRequestAllowed", "1");
        }
        chain.doFilter(req, resp);
        return;
    }

    @Override
    public void destroy() {
    }
}
